/*
/*
 * Copyright (c) 2009-2013 EvTech Project
 * All rights reserved.
 * 
 * This file is part of Game packet.
 *
 * Game packet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 *
 * Game packet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Game packet.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package fi.honkalampisaatio.utilities.math;

import java.util.ArrayList;
import java.util.Iterator;


public class AverageCounter {

	private int size;
	private int index;
	private ArrayList<Double> list;
	
	public AverageCounter(int size) {
		this.size = size;
		this.index = 0;
		list = new ArrayList<Double>();
	}
	
	public void add(double d) {
		if(this.size <= 0) {
			return;
		}
		
		if(list.size() < this.size) {
			list.add(d);
		}
		else {
			list.set(this.index, d);
		}
		this.index++;
		if(this.index >= this.size) {
			this.index = 0;
		}
	}
	
	public double getAverage() {
		if(list.isEmpty()) {
			return 0;
		}
		
		double sum = 0;
		Iterator<Double> i = list.iterator();
		while(i.hasNext()) {
			sum += i.next().doubleValue();
		}
		return sum/list.size();
	}

	//test
	public static void main(String[] args) {
		AverageCounter counter = new AverageCounter(10);
		counter.add(24);
		counter.add(15);
		counter.add(21);
		counter.add(10);
		counter.add(23);
		counter.add(13);
		counter.add(16);
		counter.add(19);
		counter.add(19);
		counter.add(14);
		counter.add(16);
		counter.add(11);
		counter.add(10);
		counter.add(19);
		counter.add(13);
		counter.add(17);
		counter.add(14);
		counter.add(14);
		counter.add(15);
		counter.add(17);
		counter.add(16);
		System.out.println(counter.getAverage());
	}

}
